<!doctype html>
<html>

<head>
  <title>Spotify插件授权码页面</title>
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
  <style type="text/css">
    #login,
    #loggedin {
      display: none;
    }

    .text-overflow {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 500px;
    }
  </style>
</head>

<body>
  <div class="container">
    <div id="login">
      <h1>请点击下方按钮授权Spotify(需要使用代理访问)</h1>
      <a href="/login" class="btn btn-primary">点击通过Spotify登录</a>
    </div>
    <div id="loggedin">
      <div id="user-profile">
      </div>
      <div id="oauth">
      </div>
      <button class="btn btn-copyAccessToken" id="none" onclick="copyToClipboard()">复制访问令牌(Access Token)</button>
      <button class="btn btn-default" id="obtain-new-token">通过刷新令牌(Refresh token)获取一个新的授权令牌(Access token)</button>
    </div>
  </div>

  <script id="user-profile-template" type="text/x-handlebars-template">
      <h1>你好, {{display_name}} !</h1>
      <div class="media">
        <div class="pull-left">
          <img class="media-object" width="150" src="{{images.0.url}}" />
        </div>
        <div class="media-body">
          <dl class="dl-horizontal">
            <dt>用户名</dt><dd class="clearfix">{{display_name}}</dd>
            <dt>用户ID</dt><dd>{{id}}</dd>
            <dt>邮箱</dt><dd>{{email}}</dd>
            <dt>Spotify地址</dt><dd><a href="{{external_urls.spotify}}">{{external_urls.spotify}}</a></dd>
            <dt>API链接</dt><dd><a href="{{href}}">{{href}}</a></dd>
            <dt>面板图片链接</dt><dd class="clearfix"><a href="{{images.0.url}}">{{images.0.url}}</a></dd>
            <dt>国家</dt><dd>{{country}}</dd>
          </dl>
        </div>
      </div>
    </script>

  <script id="oauth-template" type="text/x-handlebars-template">
      <h2>身份验证信息</h2>
      <dl class="dl-horizontal">
        <dt>授权令牌(Access token)</dt><dd class="text-overflow access_token_text">{{access_token}}</dd>
        <dt>刷新令牌(Refresh token)</dt><dd class="text-overflow">{{refresh_token}}</dd>
      </dl>
    </script>

  <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  <script>
    (function () {

      /**
       * Obtains parameters from the hash of the URL
       * @return Object
       */
      function getHashParams() {
        var hashParams = {};
        var e, r = /([^&;=]+)=?([^&;]*)/g,
          q = window.location.hash.substring(1);
        while (e = r.exec(q)) {
          hashParams[e[1]] = decodeURIComponent(e[2]);
        }
        return hashParams;
      }

      var userProfileSource = document.getElementById('user-profile-template').innerHTML,
        userProfileTemplate = Handlebars.compile(userProfileSource),
        userProfilePlaceholder = document.getElementById('user-profile');

      var oauthSource = document.getElementById('oauth-template').innerHTML,
        oauthTemplate = Handlebars.compile(oauthSource),
        oauthPlaceholder = document.getElementById('oauth');

      var params = getHashParams();

      var access_token = params.access_token,
        refresh_token = params.refresh_token,
        error = params.error;

      if (error) {
        alert('There was an error during the authentication');
      } else {
        if (access_token) {
          // render oauth info
          oauthPlaceholder.innerHTML = oauthTemplate({
            access_token: access_token,
            refresh_token: refresh_token
          });

          $.ajax({
            url: 'https://api.spotify.com/v1/me',
            headers: {
              'Authorization': 'Bearer ' + access_token
            },
            success: function (response) {
              userProfilePlaceholder.innerHTML = userProfileTemplate(response);

              $('#login').hide();
              $('#loggedin').show();
            }
          });
        } else {
          // render initial screen
          $('#login').show();
          $('#loggedin').hide();
        }

        document.getElementById('obtain-new-token').addEventListener('click', function () {
          $.ajax({
            url: '/refresh_token',
            data: {
              'refresh_token': refresh_token
            }
          }).done(function (data) {
            access_token = data.access_token;
            oauthPlaceholder.innerHTML = oauthTemplate({
              access_token: access_token,
              refresh_token: refresh_token
            });
          });
        }, false);
      }
    })();

    function copyToClipboard() {
      var input = document.getElementsByClassName('access_token_text')[0];
      var tempInput = document.createElement('textarea');
      tempInput.value = input.textContent;
      document.body.appendChild(tempInput);
      tempInput.select();
      document.execCommand('copy');
      document.body.removeChild(tempInput);
      alert('访问令牌(Access Token)已复制到剪贴板：' + input.textContent);
    }
  </script>
</body>

</html>